﻿const app = (typeof getApp === "function") ? getApp() : null;

const callCloud = options => {
  const opts = options || {};
  const {
    loadingTitle,
    showLoading = true,
    success,
    fail,
    complete
  } = opts;

  const executor = (resolve, reject) => {
    const payload = Object.assign({}, opts);
    delete payload.loadingTitle;
    delete payload.showLoading;
    delete payload.success;
    delete payload.fail;
    delete payload.complete;

    const title =
      typeof loadingTitle === "string" && loadingTitle.trim()
        ? loadingTitle.trim()
        : "正在搜索...";

    const shouldShowLoading = showLoading !== false;
    if (shouldShowLoading) {
      wx.showLoading({ title, mask: true });
    }

    const cleanup = () => {
      if (shouldShowLoading) {
        wx.hideLoading();
      }
    };

    let settled = false;
    const handleSuccess = res => {
      if (settled) return;
      settled = true;
      if (typeof success === "function") {
        success(res);
      }
      resolve(res);
    };

    const handleFail = err => {
      if (settled) return;
      settled = true;
      if (typeof fail === "function") {
        fail(err);
      }
      reject(err);
    };

    payload.success = handleSuccess;
    payload.fail = handleFail;
    payload.complete = (...args) => {
      cleanup();
      if (typeof complete === "function") {
        complete(...args);
      }
    };

    const invoke = executorFn => {
      try {
        return executorFn(payload);
      } catch (error) {
        cleanup();
        handleFail(error);
        return null;
      }
    };

    payload.success = res => {
      handleSuccess(res);
    };

    payload.fail = err => {
      handleFail(err);
    };

    payload.complete = (...args) => {
      cleanup();
      if (typeof complete === "function") {
        complete(...args);
      }
    };

    try {
      let maybePromise;
      if (app && typeof app.callCloudFunction === "function") {
        maybePromise = invoke(app.callCloudFunction.bind(app));
      } else {
        maybePromise = invoke(wx.cloud.callFunction.bind(wx.cloud));
      }

      if (maybePromise && typeof maybePromise.then === "function") {
        maybePromise.then(handleSuccess).catch(handleFail).finally(cleanup);
      }
    } catch (error) {
      cleanup();
      handleFail(error);
    }
  };

  return new Promise(executor);
};

const normalizeToMs = value => {
  if (!value) return NaN;
  if (typeof value === "object" && value.startTime) {
    return normalizeToMs(value.startTime);
  }
  if (value instanceof Date) {
    return value.getTime();
  }
  if (typeof value === "number") {
    return value < 1e12 ? value * 1000 : value;
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (/^\d+$/.test(trimmed)) {
      const numeric = parseInt(trimmed, 10);
      return numeric < 1e12 ? numeric * 1000 : numeric;
    }
    const parsed = Date.parse(trimmed);
    return Number.isFinite(parsed) ? parsed : NaN;
  }
  return NaN;
};

const padNumber = number => {
  const numeric = typeof number === "number" ? number : parseInt(number, 10);
  if (Number.isNaN(numeric)) return "00";
  return numeric < 10 ? `0${numeric}` : `${numeric}`;
};

Page({
  data: {
    searchValue: "",
    results: [],
    loading: false,
    hasSearched: false,
    errorMessage: "",
    stateText: {
      placeholder: "输入活动名称、类型或关键词试试看",
      empty: "暂时没有找到相关活动",
      ready: "搜一下，就找到~"
    }
  },

  onLoad() {
    this.imageCache = {};
  },

  onInputChange(event) {
    const value = event && event.detail ? event.detail.value : "";
    this.setData({ searchValue: value });
  },

  onSearchTap() {
    this.performSearch(this.data.searchValue);
  },

  onSearchConfirm(event) {
    const value = event && event.detail ? event.detail.value : "";
    this.performSearch(value);
  },

  onClearTap() {
    if (this.data.loading) return;
    this.setData({
      searchValue: "",
      results: [],
      errorMessage: "",
      hasSearched: false
    });
  },

  performSearch(rawValue) {
    const searchValue = typeof rawValue === "string" ? rawValue : this.data.searchValue;
    const term = (searchValue || "").trim();

    if (!term) {
      wx.showToast({
        title: "请输入搜索内容",
        icon: "none"
      });
      return;
    }

    if (this.data.loading) return;

    this.setData({
      searchValue: term,
      loading: true,
      errorMessage: "",
      hasSearched: false,
      results: []
    });

    if (typeof wx.hideKeyboard === "function") {
      wx.hideKeyboard();
    }

    callCloud({
      name: "querySearch",
      data: { searchTerms: term },
      loadingTitle: "正在搜索...",
      showLoading: false
    })
      .then(response => {
        const normalized = this.normalizeResults(this.extractResult(response));
        return this.resolveActivityImages(normalized).then(resolved => {
          this.setData({
            results: resolved,
            hasSearched: true
          });
        });
      })
      .catch(error => {
        console.error("搜索云函数失败", error);
        this.setData({
          errorMessage: "搜索失败，请稍后重试",
          hasSearched: true
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  extractResult(response) {
    if (!response) return [];
    if (Array.isArray(response)) return response;
    if (Array.isArray(response.result)) return response.result;
    if (response.result && Array.isArray(response.result.data)) {
      return response.result.data;
    }
    if (response.data && Array.isArray(response.data)) {
      return response.data;
    }
    if (response.result && Array.isArray(response.result.activities)) {
      return response.result.activities;
    }
    if (Array.isArray(response.activities)) {
      return response.activities;
    }
    return [];
  },

  normalizeResults(activities) {
    if (!Array.isArray(activities)) return [];
    return activities.map(item => {
      const safeItem = item || {};
      const times = Array.isArray(safeItem.activityStartTime)
        ? safeItem.activityStartTime
        : [];
      return {
        activityID: safeItem.activityID || "",
        activityName: safeItem.activityName || "未命名活动",
        activityImage: safeItem.activityImage || "",
        activityLocation: safeItem.activityLocation || "地点待定",
        activityTimeText: this.buildTimeText(times)
      };
    });
  },

  buildTimeText(timeList) {
    if (!Array.isArray(timeList) || timeList.length === 0) {
      return "时间待定";
    }
    const parts = timeList
      .map(value => this.formatDateTime(value))
      .filter(Boolean);
    return parts.length > 0 ? parts.join(" / ") : "时间待定";
  },

  formatDateTime(value) {
    const ms = normalizeToMs(value);
    if (!Number.isFinite(ms)) {
      return typeof value === "string" ? value : "";
    }
    const date = new Date(ms);
    const year = date.getFullYear();
    const month = padNumber(date.getMonth() + 1);
    const day = padNumber(date.getDate());
    const hours = padNumber(date.getHours());
    const minutes = padNumber(date.getMinutes());
    return `${year}年${month}月${day}日 ${hours}:${minutes}`;
  },

  resolveActivityImages(activities) {
    if (!Array.isArray(activities) || activities.length === 0) {
      return Promise.resolve([]);
    }
    const cache = this.imageCache || (this.imageCache = {});
    const pending = [];
    activities.forEach(activity => {
      const image = activity && activity.activityImage;
      if (typeof image === "string" && image.startsWith("cloud://") && !cache[image]) {
        pending.push(image);
      }
    });
    if (pending.length === 0) {
      return Promise.resolve(
        activities.map(activity => this.applyCachedImage(activity))
      );
    }
    const unique = Array.from(new Set(pending));
    return wx.cloud
      .getTempFileURL({ fileList: unique })
      .then(res => {
        const list = (res && res.fileList) || [];
        list.forEach(file => {
          if (file.status === 0 && file.tempFileURL) {
            cache[file.fileID] = file.tempFileURL;
          }
        });
        return activities.map(activity => this.applyCachedImage(activity));
      })
      .catch(err => {
        console.error("获取临时图片链接失败", err);
        return activities;
      });
  },

  applyCachedImage(activity) {
    if (!activity) return activity;
    const cache = this.imageCache || {};
    const image = activity.activityImage;
    if (typeof image === "string" && cache[image]) {
      return Object.assign({}, activity, { activityImage: cache[image] });
    }
    return activity;
  },

  handleResultTap(event) {
    const dataset =
      event && event.currentTarget ? event.currentTarget.dataset : null;
    const activityID = dataset ? dataset.id : "";
    if (!activityID) return;
    wx.navigateTo({
      url: `/pages/activity-detail/activity-detail?activityID=${encodeURIComponent(activityID)}`,
      fail: () => {
        wx.showToast({
          title: "跳转失败",
          icon: "none"
        });
      }
    });
  },

  onShareAppMessage() {}
});
